<?php
class controller_user extends model_user{
	//验证码输出
	public function verificationcode($rmt=null){
		require(PATH_ROOT.'/plus/cimage.plus.php');
		$width=72;
		$height=24;
		$img=new CImage($width, $height);
		$img->sessionName = $this->vcodeSessionName;
		$img->printimg('png');
	}
	//用户登录
	public function login(){
		if ($this->post){
			$username = $this->existsKeyInArray('username',$_POST,'S');//array_key_exists('username', $_POST) ? strval($_POST['username']) : '';
			$password = $this->existsKeyInArray('password',$_POST,'S');//array_key_exists('password', $_POST) ? strval($_POST['password']) : '';
			$vcode = $this->existsKeyInArray('vcode',$_POST,'S');//array_key_exists('vcode', $_POST) ? strval($_POST['vcode']) : '';

			if (empty($vcode)) core::error('验证码不能为空');
			if (empty($username)) core::error('账户名不能为空');
			if (empty($password)) core::error('登录密码不能为空');
			
			$sysvcode = $_SESSION['verificationcodevalue'];
			if($sysvcode!=$vcode)  core::error('验证码错误');
			if (!core::plus('validate')->username($username)) core::error('账户名格式错误');
			if(strlen($username) < 6 ) core::error('用户名不能少于6个字符');
			if(strlen($password) < 6 ) core::error('密码不能少于6个字符');
			//if(!ctype_alnum($password)) core::error('密码规则不正确');
			$user = $this->mod_userinfo_forusername($username);
			if (!$user) core::error('您输入的账户不存在');

            $encrypt_oldpass = $this->encrypt($password,'E',$user['keyt']);
			if ($encrypt_oldpass !== $user['password']) core::error($encrypt_oldpass.'您输入的密码错误');
			if (!$user['enable']) core::error('您输入的账户已被冻结，请联系管理员');

			$session = array(
				'uid' => $user['uid'],
				'username' => $user['username'],
				'session_key' => session_id(),
				'logintime' => $this->time,
				'accesstime' => $this->time,
				'loginip' => $this->ip(true),
				'client_type' => $this->client_type
			);
			$_SESSION['clienttype'] = $this->client_type;
			$session = array_merge($session, $this->get_browser());
			$this->mod_loginSaveSession($session,$user);
		} else {
			$username = array_key_exists('username', $_COOKIE) ? ' value="'.$_COOKIE['username'].'"' : '';
			$remember = (array_key_exists('remember', $_COOKIE) && $_COOKIE['remember'] == 1) ? ' checked' : '';
			$fromurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
			$fromurl = $fromurl ? $fromurl : '/';
			$tofromurl = stristr($fromurl,'reg') ? '/user/center' : $fromurl;
			$tofromurl = stristr($fromurl,'login') ? '/user/center' : $fromurl;
			$this->display('/user/login', array(
				'username' => $username,
				'fromurl' => $tofromurl
			));
		}
	}
}